package com.example.mockapiservice;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/images")
public class ImageController {

    // 图片存储路径
    private static final String IMAGE_DIRECTORY = "C:\\Users\\ZhangLeo\\Pictures\\Saved Pictures";

    /**
     * 获取图片的二进制流
     * @param fileId 文件ID参数
     * @return 图片的二进制流响应
     */
    @GetMapping("/getImage")
    public ResponseEntity<Resource> getImage(
            @RequestParam(value = "fileId", required = false) String fileId) {

        try {
            // 检查图片目录是否存在
            File directory = new File(IMAGE_DIRECTORY);
            if (!directory.exists() || !directory.isDirectory()) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }

            // 获取目录中的第一个图片文件（实际应用中应该根据fileId查找对应文件）
            File[] imageFiles = directory.listFiles((dir, name) -> {
                String lowercaseName = name.toLowerCase();
                return lowercaseName.endsWith(".jpg") || lowercaseName.endsWith(".jpeg") || 
                       lowercaseName.endsWith(".png") || lowercaseName.endsWith(".gif");
            });

            if (imageFiles == null || imageFiles.length == 0) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }

            File imageFile = imageFiles[Integer.parseInt(fileId)];
            Path imagePath = Paths.get(imageFile.getAbsolutePath());
            Resource resource = new FileSystemResource(imageFile);

            // 获取文件的媒体类型
            String contentType = Files.probeContentType(imagePath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentDispositionFormData("attachment", imageFile.getName());
            headers.setContentLength(imageFile.length());

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}